import { App } from "../../src/App";
import { Singleton } from "../../src/core/Class";
import { EventConst } from "../../src/core/EventConst";
import MailSys from "../src/system/MailSys";
import NoticeSys from "../src/system/NoticeSys";
import PackSys from "../src/system/PackSys";
import PropSys, { PropType } from "../src/system/PropSys";
import { ProtocolMain } from "./Protocol";
import RedPoint from "./system/RedPointSys";

// 房间数据
interface RoomData {
    name: string, 
    id: number, 
    score: number, 
    icon: number,
};
// 用户数据结构
export interface UserData {
	UserName: string,
    OpenID:string,
	Avatar: number,
	Coin: number,
	UserID: number,
    Token:string,
};

interface LoginData{
    lastTime:number,
    loginType:number, // LoginType
    token:string,
    svrUrl:string,
}

export default class BaseModel extends Singleton<BaseModel>{
    protected _roomData:any = null; // RoomConfST
    protected _loginData:LoginData = null;
    protected _userData:UserData = null;
    protected _isPlaying:boolean = false; // 是否游戏进行中
    protected _nodePool:cc.NodePool = null; // 结点池
    protected _isTrusteeship:boolean = false; // 是否托管状态
    protected _isSingle:boolean = false; // 是否单机
    protected _rankInfo:any[] = [];    // 排行信息
    protected _isInRoom:boolean = false; // 是否在房间里

    public get userInfo():UserData{return this._userData;}
    public get token():string{return this._userData.Token;};
    public get isPlaying():boolean {return this._isPlaying;}
    public get rankInfo():any[]{return this._rankInfo;}
    public get isTrusteeship():boolean{return this._isTrusteeship;}
    public get isSingle():boolean{return this._isSingle;}
    public get isInRoom():boolean{return this._isInRoom;}
    
    public set playing(is:boolean){this._isPlaying=is;}

    public setUser(val:any,key?:string){
        (key && key.length > 0) ? (this._userData[key] = val):this._userData = val;
    }

    public playEffect(name: string){
        App.Audio.play(`sound/${name}:game`);
    }

    public entryRoom(cfg:any){this.onEntry(cfg);}
    public exitRoom() {this.onExit();}
    public startGame(cfgID:number){this.onStart(cfgID);}
    public fireCard(roomID:string,list:number[]){ this.onFireCard(roomID,list);}
    public login(type:number){this.onLogin(type);}
    public logout(){this.onLogout();}
    public trusteeship(){this.onTrusteeship();}

    public get MainProtocol():number{
        if (App.ModuleName === 'RunFast') 
            return ProtocolMain.RunFast_CODE;
        else if (App.ModuleName === 'Landlord')
            return ProtocolMain.DDZ_CODE;
        return ProtocolMain.Unknow;
    }

    /**
     * 获取房间数据，
     */
    public get roomData():any {return this._roomData;}


    public insertPoker(parent:cc.Node,prefab:cc.Prefab,pos?:cc.Vec2):cc.Node{
        const it:cc.Node = this._nodePool.get() || (prefab ? cc.instantiate(prefab):null);
        if (App.Util.isInvalid(it) || App.Util.isInvalid(parent)){
            throw(new Error(`BaseModel.createPoker(parent=null || item=null)`));
        }
        it.parent = parent;
        it.zIndex = parent.childrenCount-1;
        it.setPosition(pos || cc.v2(0,0));
        return it;
    }

    public removePoker(node:cc.Node|cc.Component):void{
        if (!node) return ;
        
        if (node instanceof cc.Component) node = node.node;
        // 这里进行简单的重置，恢复基本属性
        node.scale = 1;
        node.opacity = 255;
        cc.tween(node).stop();
        this._nodePool.put(node);
    }

    //----------------------------------------------------------
    // 以下几个方法需要具体的游戏GameModule实现
    protected onInit(){
        this._loginData = App.getLocalStorage(App.LOCAL_KEY.LOGIN);
        App.Avatar.init(App.getCfg(`avatars`));
        App.Event.on(EventConst.LOGIN_SUCCESS, (type:number) => {
            this._initGameSystem();
            App.runScene('HallScene:hall');
            App.logout = false;
        }, this);
    }

    protected onDestroy(){ 
        // 销毁各功能系统，在退出登陆或者切换账号的时候触发
        RedPoint.destroy();
        PropSys.destroy();
        NoticeSys.destroy();
        PackSys.destroy();
        MailSys.destroy();
    }

    protected onStart(cfgID:number){};
    protected onEntry(cfg:any){}
    protected onFireCard(roomID:string,list:number[]){}
    protected onExit(){}
    protected onLogin(type:number){}
    protected onLogout(){};
    protected onSocket(is:boolean){}
    protected onTrusteeship(){}
    // 以上几个方法需要具体的游戏GameModule实现
    //----------------------------------------------------------

    /**
     * 初始化游戏系统
     */
    private _initGameSystem(){
        RedPoint.init();    // 红点系统 
        PropSys.init();     // 道具系统
        NoticeSys.init();   // 通知公告系统
        PackSys.init();     // 背包系统
        MailSys.init();     // 邮件系统
    }
}